package cn.comtom.ewbs.signature.controller;

import java.io.IOException;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.comtom.ewbs.signature.common.enums.BasicError;
import cn.comtom.ewbs.signature.common.vo.request.CertImportReq;
import cn.comtom.ewbs.signature.common.vo.request.DataReq;
import cn.comtom.ewbs.signature.common.vo.response.ApiEntityResponse;
import cn.comtom.ewbs.signature.common.vo.response.ApiResponse;
import cn.comtom.ewbs.signature.common.vo.response.ApiResponseBuilder;
import cn.comtom.ewbs.signature.service.ISignatureService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

//git.comtom.cn:18000/ct-ewbsv2.0/ct-ewbsv2.0.git

@Slf4j
@RestController
@RequestMapping("/open/sign")
@Api(tags = "通用数字签名服务")
public class SignatureController extends BaseController{

    @Autowired
    private ISignatureService signatureService;
    
    @ApiImplicitParams({
        @ApiImplicitParam(value = "待验签文件",name = "xmlFile",required = true,allowMultiple = true,dataType = "MultipartFile")
    })
    @PostMapping(value="/verifySignByFile",consumes = "multipart/*")
    @ApiOperation(value = "验证签名", notes = "文件不能超过30M大小")
    public ApiResponse verifySign(@RequestParam(name = "xmlFile")  MultipartFile xmlFile, @RequestParam(name = "signValue")String signValue){
        if(xmlFile == null || StringUtils.isBlank(signValue)){
            return ApiResponseBuilder.buildEntityError(BasicError.PARAM_VALID_ERROR);
        }
		try {
			Boolean b = signatureService.verifyFileSign(xmlFile.getBytes(), signValue);
			log.info("验证签名verifySign,filename:{},signValue:{},result:{}", xmlFile.getOriginalFilename(),signValue,b);
			if(b){
	            return ApiResponse.ok();
	        }
		} catch (Exception e) {
			e.printStackTrace();
			return ApiResponseBuilder.buildError(BasicError.VERIFY_SIGN_FAILURE.getCode(), e.getMessage());
		}
		return ApiResponseBuilder.buildEntityError(BasicError.VERIFY_SIGN_FAILURE);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ApiImplicitParams({
        @ApiImplicitParam(value = "待签名文件",name = "xmlFile",required = true,allowMultiple = true,dataType = "MultipartFile")
    })
	@PostMapping(value="/getSignByFile",consumes = "multipart/*")
    @ApiOperation(value = "获取签名", notes = "文件不能超过30M大小")
    public ApiEntityResponse<String> getSign(@RequestParam(name = "xmlFile")  MultipartFile xmlFile){

        if(xmlFile == null){
            return ApiResponseBuilder.buildEntityError(BasicError.PARAM_VALID_ERROR);
        }
		try {
			String sign = signatureService.getFileSign(xmlFile.getBytes());
			ApiEntityResponse ok = ApiEntityResponse.ok(BasicError.OK_KEY_VALUE);
			ok.setData(sign);
			log.info("生成签名getSign,fileName:{},sign:{}",xmlFile.getOriginalFilename(),sign);
			return ok;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ApiResponseBuilder.buildEntityError(BasicError.VERIFY_SIGN_FAILURE);

    }

    @PostMapping("/getSignByStr")
    @ApiOperation(value = "获取签名", notes = "接收文本字符串")
    public ApiEntityResponse<String> getSignByStream(@RequestBody @Valid DataReq data) {
        try {
			String sign = signatureService.getByteSign(data.getData());
			ApiEntityResponse ok = ApiEntityResponse.ok(BasicError.OK_KEY_VALUE);
			ok.setData(sign);
			log.info("生成签名getSign, sign:{}",sign);
			return ok;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiResponseBuilder.buildEntityError(BasicError.VERIFY_SIGN_FAILURE);
    }

    @PostMapping(value="/verifySignByStr")
    @ApiOperation(value = "验证签名", notes = "接收文本字符串")
    public ApiResponse verifySignByStream(@RequestBody @Valid DataReq data){
        if(StringUtils.isBlank(data.getSignValue())){
            return ApiResponseBuilder.buildEntityError(BasicError.PARAM_VALID_ERROR);
        }
		try {
			Boolean b = signatureService.verifyByteSign(data.getData(),data.getSignValue());
			log.info("验证签名verifySign,signValue:{},result:{}", data ,data.getSignValue(),b);
			if(b){
	            return ApiResponse.ok();
	        }
		} catch (Exception e) {
			e.printStackTrace();
			return ApiResponseBuilder.buildError(BasicError.VERIFY_SIGN_FAILURE.getCode(), e.getMessage());
		}
		return ApiResponseBuilder.buildEntityError(BasicError.VERIFY_SIGN_FAILURE);
    }

    @PostMapping(value="/importCert")
    @ApiOperation(value = "导入证书", notes = "导入证书")
    public ApiResponse importCert(@RequestBody @Valid CertImportReq req){
        if(req==null || req.getCerts().size()==0){
            return ApiResponseBuilder.buildEntityError(BasicError.PARAM_VALID_ERROR);
        }
        try {
        	Boolean b = signatureService.importCert(req.getCerts());
	        log.info("导入证书importCerth,result:{}", b);
			if(b){
	            return ApiResponse.ok();
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiResponseBuilder.buildEntityError(BasicError.IMPORT_CERT_FAILURE);
    }

    @PostMapping(value="/importCertauthList")
    @ApiOperation(value = "导入信任列表", notes = "导入信任列表")
    public ApiResponse importCertauthList(@RequestParam(name = "certauthList")  String certauthList){
		try {
			Boolean b = signatureService.importCertauthList(certauthList);
			log.info("导入证书链importCertauthList，result:{}", b);
			if(b){
	            return ApiResponse.ok();
	        }
		} catch (Exception e) {
			e.printStackTrace();
			return ApiResponseBuilder.buildError(BasicError.VERIFY_SIGN_FAILURE.getCode(), e.getMessage());
		}
		return ApiResponseBuilder.buildEntityError(BasicError.IMPORT_CERTH_FAILURE);
    }

}
